package org.chipu.shared.util.singletons;

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class WindowsUtils {
	private static Logger logger = Logger.getLogger(WindowsUtils.class.getName());

	public static void setLogger(Logger l) {
		if (l != null)
			logger = l;
	}

	public static Process runCommand(String cmd) {
		return runCommand(cmd, true, true, true);
	}

	public static Process runCommand(String cmd, boolean wait, boolean printStdOut, boolean printErrOut) {
		logger.finer("Executing command '" + cmd + "'");
		try {
			String[] command = {System.getProperty("os.name").equals("Windows 95")? "command.com": "cmd.exe", "/C", cmd};
			final Process process = Runtime.getRuntime().exec(command);
			if (printStdOut)
				new Thread() {
					@Override
					public void run() {
						try {
							// InputStream is = process.getInputStream();
							// byte[] buffer = new byte[1024];
							// for(int count = 0; (count = is.read(buffer)) >= 0;)
							// logger.finest("\t'" + new String(buffer, 0, count - 1) + "'");
							BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
							String line = null;
							while((line = br.readLine()) != null)
								logger.finest("\t" + line);
						} catch(Exception ex) {
							logger.log(Level.WARNING, "", ex);
						}
					}
				}.start();
			if (printErrOut)
				new Thread() {
					@Override
					public void run() {
						try {
							BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()));
							String line = null;
							while((line = br.readLine()) != null)
								logger.warning("\t" + line);
						} catch(Exception ex) {
							logger.log(Level.WARNING, "", ex);
						}
					}
				}.start();
			if (wait) {
				int returnCode = process.waitFor();
				logger.finer("\tReturn code = " + returnCode);
			}
			return process;
		} catch(Throwable ex) {
			logger.log(Level.WARNING, "", ex);
		}
		return null;
	}

	public static String getSubnetMask(final Logger logger) {
		final Process p = runCommand("ipconfig", false, false, true);
		final String[] rta = new String[1];
		new Thread() {
			@Override
			public void run() {
				try {
					BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
					String line = null;
					while((line = br.readLine()) != null)
						// System.out.println(line);
						// if (line.contains("IP")&&line.contains(". . . ."))
						// rta[0] = line.substring(line.indexOf(": ")+2).trim();
						if (line.contains(": 255"))
							rta[0] = line.substring(line.indexOf("255")).trim();
				} catch(IOException ex) {
					logger.log(Level.WARNING, "", ex);
				}
			}
		}.start();
		try {
			p.waitFor();
		} catch(InterruptedException e) {
			logger.log(Level.WARNING, "", e);
		}
		return rta[0];
	}
}